// subpage/pages/charge/charge.js
import service from '../../../utils/request'
import { formatTime, formatDate,timeToDate } from '../../../utils/util'
import { store } from '../../../store/store'
import { createStoreBindings } from 'mobx-miniprogram-bindings'
// import Dialog from '../../../@vant/weapp/dist/dialog/dialog'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isVip:false,
    snType: false,
    isRead: false,
    orderData: {
      coupon: '',
      sn: '',
      plate: '',
      payType: '2'
    },
    siteId: '',
    rate:{},
    groupRate:{},
    groupPrice:'',
    rateList:[],
    show: false,
    canuseCoupon: 0,
    text:'开始充电',
    siteName:'',
    islogin:false,
    couponMsg: '请选择',
    showToast: true,
    ToastType: '',
    balance: 0,
    lowPrice:0,
    canUseTime:'',
    notUseReason: false,
    notType: 99,
    reason: '集团支付不可用',
    isGroup: false,
    groupBalance:0,
    canUseCompanyRate: true,
    overPrice: {}
  },
  showPrice() {
    console.log('点击了-----')
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({ show: false });
  },
  onChangeType(event){
    this.setData({
      ['orderData.payType']: event.detail,
    });
  },
  onCloseDia(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  onRead(){
   this.setData({
     isRead: !this.data.isRead 
   })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('页面显示',options)
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['updateCars'],
    })
    if(options.sn){
      var sn = options.sn
      // var sn = '0100001000000101'
      var arr1 = sn.split("/");
      let len = arr1.length -1
      sn = arr1[len]
      console.log('snsns',sn)
      let sn_ = sn.replace(/-/g,'')
      this.setData({
        ['orderData.sn']:sn_,
      })
      // this.isCanuse()
    }
    if (options.q !== undefined) {
      var scan_url = decodeURIComponent(options.q);
      
      console.log(scan_url);
      let qsn = scan_url.replace(/-/g,'')
      let realSn = qsn.substring(qsn.length-18)
      console.log('转码后',realSn)
      this.setData({
        ['orderData.sn']:realSn,
      })
      }
    if(options.coupon){
      console.log('已选择一张')
      this.setData({
        ['orderData.coupon']:options.coupon,
        couponMsg: '已选择1张'
      })
    }else{
    }
    this.setShowToast()
    // this.setPhone()
  },
  getCompanyTime(){
    let that = this
    let resu =  service("GET", '/group/use/time/list').then(res => {
      console.log('大客户时段', res)
      if (res.data.code == 0) {
        wx.setStorageSync('userPhone',true)
          this.setData({
            showToast: wx.getStorageSync('userPhone'),
            ToastType: 2
          })
          that.getUser()
          // that.getBalance()
          that.getRate()
          that.getSite()
          that.canuseCoupon()
      }
    })
  },
  setShowToast() {
    this.setData({
      showToast: wx.getStorageSync('token'),
      ToastType: 1
    })
    if(this.data.showToast) this.setPhone()
  },
  setPhone(){
    this.setData({
      showToast: wx.getStorageSync('userPhone'),
      ToastType: 2
    })
  },
  goSetPhone(){
      wx.navigateTo({
        url: '/subpage/pages/bandphone/bandphone',
      })
  },
  getPhoneNumber (e) {
    console.log('我获取了手机号', e)
    let that = this
    let resu =  service("POST", '/login/phone', {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    }).then(res => {
      console.log('手机号返回值', res)
      if (res.data.code == 0) {
        wx.setStorageSync('userPhone',true)
          this.setData({
            showToast: wx.getStorageSync('userPhone'),
            ToastType: 2
          })
          that.getUser()
          // that.getBalance()
          that.getRate()
          that.getSite()
          that.canuseCoupon()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  readOn(){
    this.setData({
      isRead: false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    console.log('onshow')
    this.setShowToast()
    if(!this.data.showToast) return
    this.getUser()
    // that.getBalance()
    this.getRate()
    this.getSite()
    this.canuseCoupon()
  },
  //关闭弹窗
  cancelToast() {
    this.setData({
      showToast: true
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  gologin(){
    wx.navigateTo({
      url: "/subpage/pages/login/login"
    })
  },
  getUser() {
    let that = this
    let resu =  service("GET", '/user/info', {}).then(res => {
      console.log('初始化个人信息', res)
      if (res.data.code == 0) {
        let notUseReason = false
        let isGroup = false
        if(res.data.user.group){
          let group = res.data.user.group
          let time = new Date().getTime()
          if(group.state == 1 && group.groupPayment==1 && (time >=group.effectTime && time<=group.invalidTime)){
            // that.getCompanyTime()
            that.getCompanyPrice()
          }else{
            console.log('用户不可用', 1)
            notUseReason = false
            that.setData({
              notType: 1
            })
          }
          if(group.state != 1 || (time < group.effectTime || time > group.invalidTime)){
            that.setData({
              canUseCompanyRate: false
            })
          }
          isGroup = true
        }else{
          isGroup = false //是否显示集团支付
        }
        that.setData({
          ['orderData.plate']:res.data.user.plate,
          islogin: true,
          notUseReason: notUseReason,
          isGroup: isGroup,
          isVip: res.data.user.isVip
        })
      }
      if (res.data.code == 414) {
        wx.navigateTo({
          url: "/subpage/pages/login/login?len=2"
        })
      }
    })
  },
  //创建订单
  // createOrder() {
  //   wx.navigateTo({
  //     url: '/subpage/pages/orderdetail/orderdetail',
  //   })
  // },
  //优惠券
  useCoupon() {
    let that = this
    wx.navigateTo({
      url: '/subpage/pages/usecoupon/usecoupon',
      events:{
				onSelect(res){
          console.log(res);
          if(!res || res == 'undefine'){
            that.setData({
              ['orderData.coupon']:'',
              couponMsg:'可选择优惠券'
            })
          }else{
            that.setData({
              ['orderData.coupon']:res.id,
              couponMsg:'已选择'+res.price+'元优惠券'
            })
          }
					
				}
			}
    })
  },
  //可用优惠券数量
  canuseCoupon(){
    let that = this
    let res = service('GET','/coupon/available').then(result => {
      
      if(result.data.code == 0){
        let list = result.data.list.length
        console.log('优惠券', list)
        that.setData({
          canuseCoupon: list,
          
        })
        if(!that.data.orderData.coupon){
          console.log('已选择',that.data.orderData.coupon)
          that.setData({
            couponMsg: '可用'+list+'张'
          })
        }
        
      }
      
    })
  },
  //费率问题
  getRate(){
    let that = this
    let thisTime =new Date().getTime()
    let dates = formatTime(new Date())
    console.log('当前时间',dates)
    let res = service('GET','/iot/rates/gun/'+this.data.orderData.sn).then(result => {
      console.log('费率', result)
      if(result.data.code == 0){
        let list = result.data.list
        let data = result.data.list
        var confirmRate = ''
        let some = data.map(item => {
          item.begin_time =item.beginTime 
          item.end_time = item.endTime 
          item.coupon = item.discount
          item.yuan = (item.electric + item.service).toFixed(3)
          // item.total = (item.electric + item.service -item.discount).toFixed(3)
          item.amouts = (item.electric + item.service -item.discount).toFixed(3)
          item.beginTime = new Date(dates+' '+item.beginTime).getTime()
          if(item.endTime == "00:00:00"){
            item.endTime = "23:59:59"
          }
          item.endTime = new Date(dates+' '+item.endTime).getTime()
          return item
        })
        .filter(item => (item.beginTime <= thisTime && item.endTime >= thisTime))

        //2、时间段
        let useTime = {}
        let canUseTime = {}
        let time = new Date().getTime()
        // if(result.data.groups){
        //   useTime = result.data.groups.times
        //   useTime.map(item => {
        //     var begin = timeToDate(item.beginTime, new Date())
        //     var end = timeToDate(item.endTime, new Date())
        //     console.log('可使用时间', item, begin, end, time)
        //      if(begin <= time && time<= end){
        //        canUseTime = item
        //      }
        //   })
        //   console.log('时间段不可用', canUseTime)
        //   if(!canUseTime.beginTime){
        //     that.setData({
        //       notType: 2 //时间段不可用
        //     })
        //   }
        // }
        // 3、站点费率
        var groups = ''
        let groupsPrice = {}
        if(result.data.groups){
          groupsPrice = result.data.groups.list
          let times = result.data.groups.times
          groupsPrice.map((item, index) => {
            item.begin_time =item.beginTime 
            item.end_time = item.endTime 
            item.yuan = (item.electric + item.service).toFixed(3)
            item.coupon = item.service - (item.service * item.discount)
            item.total = (item.electric + item.service -item.discount).toFixed(3)
            item.amouts = (item.electric + item.service -item.discount).toFixed(3)
            item.beginTime = new Date(dates+' '+item.beginTime).getTime()
            if(item.endTime == '00:00:00'){
              item.endTime = new Date(dates+' '+'23:59:59').getTime()
            }else{
              item.endTime = new Date(dates+' '+item.endTime).getTime()
            }
            if(item.beginTime <= thisTime && item.endTime >= thisTime){
              groups = item
            }
            return item
          })
          console.log('groups',groups , groups)
          if(!groups && that.data.notType !=1){
            that.setData({
              notType: 3 //时间段不可用
            })
          }
          if(groups){
            let confirm = times.map((item, index) => {
              item.beginTime = new Date(dates+' '+item.beginTime).getTime()
              item.endTime = new Date(dates+' '+item.endTime).getTime()
              if(item.beginTime <= groups.beginTime && item.endTime >= groups.endTime){
                confirmRate = groups
              }
            })
            console.log('confirmRate',confirmRate)
            if(!confirmRate){
              that.setData({
                notType: 2 //时间段不可用
              })
            }
          }
          console.log('groupsPrice',groupsPrice, groups, confirmRate)
         
        }
        
        let payType = (canUseTime && groupsPrice.length >0) ? '1' : '2'
        that.setData({
          rateList:list,
          rate: some[0],
          groupPrice: confirmRate,
          ['orderData.payType']:payType,
          groupRate: canUseTime,
        })
      }
      
    })
  },
      //集团钱包
    getCompanyPrice() {
        let that = this
        let res = service('GET', '/group/user/wallet/info').then(result => {
          console.log('集团钱包',result)
          if(result.data.code==0){
            if(result.data.info.balance <=0){
              that.setData({
                notType: 4 //余额不足
              })
            }
            that.setData({
              groupBalance: result.data.info.balance,
            })
          }
          
        })
      },
  //判断充电桩是否可以使用
  isCanuse(){
    let that = this
    let res = service('GET','/order/gun/available/'+this.data.orderData.sn).then(result => {
      if(result.data.code !== 0){
        if(!result.data.available){
          wx.showToast({
            title: '该充电枪暂时不能使用',
            icon:'none'
          })
         
        }
      }
    })
  },
  //充电桩信息
  getSite (){
    let that = this
    let res = service('POST','/iot/site/gun/'+this.data.orderData.sn).then(result => {
      console.log('充电站信息',result)
      // return
      if(result.data.code == 0){
        if(result.data.list.length > 0){
          this.setData({
            siteName: result.data.list[0].name,
            siteId: result.data.list[0].id,
           })
           that.getParking(that.data.siteId)
        }else{
          console.log('充电码吧不正确')
          this.setData({
            snType: true
          })
          return 
        }
      }
    })
  },
      //详情
      getParking(siteId){
        let that = this
        let res = service("GET", '/parking/seat/'+siteId).then(result => {
          console.log('result',result)
          that.setData({
            overPrice: result.data.seat
          })
        })
        },

  //集团钱包可用时间段
  getCompanyTime() {
    let that = this
    let resu =  service("GET", '/group/use/time/list', {}).then(res => {
      console.log('集团钱包可用时间段', res)
      let time = new Date().getTime()
      let canUseTime = {}
      if (res.data.code == 0) {
        let data = res.data.list
        data.map(item => {
          var begin = timeToDate(item.beginTime, new Date())
          var end = timeToDate(item.endTime, new Date())
          // console.log('可使用时间', item, begin, end, time)
           if(begin <= time && time>= end){
             canUseTime = item
           }
        })
        let notUseReason = canUseTime ? true : false
        if(!canUseTime){
          that.setData({
            notType: 2
          })
        }
        let payType = notUseReason ? '1' : '2'
        that.setData({
          notUseReason: notUseReason,
          // canUseTime: canUseTime,
          groupRate: canUseTime,
          reason: '该时间段不支持',
          ['orderData.payType']:payType
        })
      }
      if (res.data.code == 414) {
        wx.navigateTo({
          url: "/subpage/pages/login/login?len=2"
        })
      }
    })
  },
  //集团站点费率

  //创建订单
  createOrder() {
    let that = this
    console.log('ssss',this.data.orderData)
    if(!that.data.orderData.plate){
      wx.showToast({
        title: '请先完善车牌号',
        icon:"none"
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/subpage/pages/carbeand/carbeand',
          events:{
            onCar(res){
              console.log(res);
              if(!res || res == 'undefine'){
                that.setData({
                  ['orderData.plate']:'',
                  carMsg:'请完善车牌号'
                })
              }else{
                that.setData({
                  ['orderData.plate']:res,
                })
              }
              
            }
          }
        })
      }, 500);
      return 
    }
    service("GET", "/order/balance/available").then(des => {
      console.log(des)
      if (des.data.code ==0){
        if(!des.data.available){
         this.setData({
           showToast: false,
           ToastType: 3,
           balance: des.data.balance,
           lowPrice: des.data.low
         })
          return
        }
        // ['orderData.payType']: event.detail,
        let payType = (that.data.notType==99 && this.data.orderData.payType ==1) ? '1': '2'
        const {coupon, sn, plate  } = that.data.orderData
        that.payOrder(coupon, sn, plate, payType)
        
        
      }
    })
    },
    payOrder(coupon, sn, plate, payType){
      let that = this
      // console.log(res)
      that.setData({
        text: '开始充电...'
      })
      let result = service('POST','/order/create',{coupon, sn, plate, payType}).then(res => {
        console.log('创建订单',res)
        if(res.data.code ==0){
           //订阅消息
        wx.requestSubscribeMessage({
          tmplIds: ['YuIWF4w_WJZROeKYz7_GiMfDqeK3TDHQ1Vm4gLnrmdE','WC2ob95jsUv1bWOkLehC9LfOdeTXm3th-qB4POQ31zc'],
          success(res){
            // that.payOrder(coupon, sn, plate)
            console.log('success')
          },
          fail(){
            console.log('fail')
            // that.payOrder(coupon, sn, plate)
          },
          complete()  {
            console.log('complete')
            wx.navigateTo({
              url: '/subpage/pages/detail/detail?oid='+res.data.oid+'&go=charge',
            })
          }
        })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
  
      })
    },

    //充值余额
    chargeBalance(){
      wx.navigateTo({
        url: '/subpage/pages/balance/balance',
      })
    },

    //完善车牌号
    editPlate() {
      let that  = this
      wx.navigateTo({
            url: '/subpage/pages/carbeand/carbeand',
            events:{
              onCar(res){
                console.log(res);
                if(!res || res == 'undefine'){
                  that.setData({
                    ['orderData.plate']:'',
                  })
                }else{
                  that.setData({
                    ['orderData.plate']:res,
                  })
                }
                
              }
            }
          })
    },

})